package at.fhj.itm.refactor;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;

import at.fhj.itm.generator.SqlCodeGenerator;
import at.fhj.itm.generator.postgres.PostgresSqlCodeGenerator;
import at.fhj.itm.metadata.DepdendencyProvider;
import at.fhj.itm.metadata.impl.postgres.PostgresDependencyProvider;
import at.fhj.itm.metadata.impl.postgres.PostgresMetadataProvider;
import at.fhj.refactor.refactorings.postgres.PostgresSplitTable;

public class PostgresRefactoringSuiteAssembler extends RefactoringSuiteAssembler {

	@Override
	public RefactoringSuite createRefactoringSuite(String jdbcConnection,
			String user, String pass) {
		
		try{
			Connection connection = establishConnection(jdbcConnection, 
					user, pass);
			PostgresMetadataProvider metadataProvider = new PostgresMetadataProvider(connection);
			DepdendencyProvider dependencyProvider = new PostgresDependencyProvider(metadataProvider,
					connection);
			SqlCodeGenerator generator = new PostgresSqlCodeGenerator();
			List<Refactoring> refactorings = new ArrayList<Refactoring>();
			refactorings.add(new PostgresSplitTable((DepdendencyProvider)
					dependencyProvider));
			
			return new RefactoringSuite(refactorings, metadataProvider, dependencyProvider, 
					generator, connection);
			
		}
		catch (Exception e) {
			throw new RefactorException("Error while assembling refactoring suite", e);
		}
	}

	@Override
	protected void loadJdbcDriver() throws ClassNotFoundException {
		Class.forName("org.postgresql.Driver");
		
	}

	@Override
	protected Connection establishConnection(String connectionString,
			String user, String pass) throws SQLException {
        Properties props = new Properties();
        props.setProperty("user", user);
        props.setProperty("password", pass);

        Connection connection = DriverManager.getConnection(connectionString, 
        		props);
        
        return connection;
	}

}
